package main

import (
	"fmt"
	"net/http"
	"note-go/pkg/database"
	"note-go/pkg/redis"
	"note-go/routes"
	"note-go/util"
	"path/filepath"
	"strings"

	"github.com/gin-contrib/multitemplate"
	"github.com/gin-gonic/gin"
)

func loadTemplates(templatesDir string) multitemplate.Renderer {
	r := multitemplate.NewRenderer()
	layouts, err := filepath.Glob(templatesDir + "/layouts/*.tmpl")
	if err != nil {
		panic(err.Error())
	}
	includes, err := filepath.Glob(templatesDir + "/includes/*.html")
	if err != nil {
		panic(err.Error())
	}
	// 为layouts/和includes/目录生成 templates map
	for _, include := range includes {
		layoutCopy := make([]string, len(layouts))
		copy(layoutCopy, layouts)
		files := append(layoutCopy, include)
		r.AddFromFiles(filepath.Base(include), files...)
	}
	codes, err := filepath.Glob(templatesDir + "/codes/*.html")
	if err != nil {
		panic(err.Error())
	}
	for _, code := range codes {
		r.AddFromGlob(filepath.Base(code), code)
	}
	noLayouts, err := filepath.Glob(templatesDir + "/nolayout/*.html")
	if err != nil {
		panic(err.Error())
	}
	for _, nolayout := range noLayouts {
		r.AddFromGlob(filepath.Base(nolayout), nolayout)
	}
	return r
}

func main() {
	gin.SetMode(gin.ReleaseMode)
	ginServer := gin.Default()

	redis.InitRedis()
	database.InitDB()

	ginServer.Use(func(c *gin.Context) {
		if c.Request.RequestURI == "/favicon.ico" || strings.HasPrefix(c.Request.RequestURI, "/static/") {
			c.Next()
			return
		}
		c.Next()
	})

	ginServer.HTMLRender = loadTemplates("./templates")
	ginServer.Static("/static", "./static")
	ginServer.StaticFile("/favicon.ico", "./static/favicon.ico")
	ginServer.NoRoute(func(c *gin.Context) {
		if strings.HasPrefix(c.Request.URL.Path, "/.well-known") {
			c.AbortWithStatus(http.StatusNoContent)
			return
		}
		c.HTML(http.StatusNotFound, "404.html", gin.H{})
	})
	ginServer.Use(func(c *gin.Context) {
		if strings.HasPrefix(c.Request.URL.Path, "/static/") {
			c.Header("Cache-Control", "public, max-age=31536000") // 缓存 1 年
		}
		c.Next()
	})

	routes.RegisterUserRoutes(ginServer)
	routes.RegisterAuthRoutes(ginServer)
	//ginServer.POST("/s/reload", pages.Reload)
	//ginServer.POST("/v1/api/path/add", pages.PathAdd)
	//ginServer.POST("/v1/api/path/delete", pages.PathDelete)

	// 启动Web管理界面监听
	go func() {
		fmt.Printf("Web configuration interface address: %s:%d%s", "http://127.0.0.1", 24418, util.GetNewLine())
		_ = ginServer.Run(":24418")
	}()
	//util.OpenBrowser("http://127.0.0.1:24418")

	select {}
}
